<?php

require __DIR__ . '/../bootstrap.php';

$em = require __DIR__ . '/../example/em.php';

//$em->getConnection()->exec("update biling set cashed = 0");
//$em->getConnection()->exec("update user set balance = 0");  

$sql = "
    select `user`.id, sum(biling.amount) as amount from `user`
        inner join sim_owner on `user`.id = sim_owner.user_id
        inner join biling on sim_owner.sim_id = biling.phone 
    where sim_owner.`state` = 1
        and biling.cashed = 0 
        and biling.type = 'FILLUP'
    group by `user`.id 
    ";

$rows = $em->getConnection()->query($sql)->fetchAll();

// var_dump($rows);

// карта начисления бонусов

$mapBonus = array(
    // админ
    '0' => function ($admin, $sum) {
        $admin->addBalance($sum);

    },
    // агент        
    '1' => function ($agent, $sum) {
        $proc = $sum / 100 * $agent->getBonus();
        $agent->addBalance($proc);
        $agent->getParent()->addBalance($sum - $proc);
    },
    // субагент
    '2' => function ($subAgent, $sum) {
        $agent = $subAgent->getParent();
        $admin = $agent->getParent();
        $procAgent = $sum / 100 * $agent->getBonus();
        $procSubAgent = $sum / 100 * $subAgent->getBonus();
        $agent->addBalance($procAgent);
        $subAgent->addBalance($procSubAgent);
        $admin->addBalance($sum - $procAgent - $procSubAgent);
    },
);


// начисляем бонусы
//include($_SERVER['DOCUMENT_ROOT'] . '/jbdump/init.php');
foreach ($rows as $row) {
    $sum = $row['amount'];
    $repo = $em->getRepository('Entity\User');
    $user = $repo->find($row['id']);
    $old_balance = $user->getBalance();
    //echo $user->getBonus() . '<br>';
    //jbdump($user, 0, 'myLoveVariable');
    $mapBonus[$user->getLevel()]($user, $sum);
    $credited=$user->getBalance()-$old_balance;

    $sql = "INSERT INTO `balance` (`user_id`, `sum`, `old_balance`, `credited`, `current_balance`, `user_rate`, `date`) VALUES ({$user->getId()}, $sum, $old_balance, $credited, {$user->getBalance()}, {$user->getBonus()}, now())";
    $em->getConnection()->exec($sql);

    //echo $user->getName() . ' ------ ' . $user->getBalance() . '--' . $sum . "<br/>";

    // блокируем уже рассчитанное


    blockedBilling($user, $em);

}
//exit();
$em->flush();

function blockedBilling($user, $em)
{
    $sql = "
    update biling set cashed = 1, date_cashed = now()
    where phone in (
        select sim_id from sim_owner
        where user_id = {$user->getId()}
        )
        and biling.cashed = 0
        and biling.type = 'FILLUP'
    ";
    $em->getConnection()->exec($sql);
}


